using System;
using UnityEngine;
using Unity.VisualScripting;
using LS.GameSystem;

namespace LS.VisualScripting
{
    public class CreateGameSystem: GameSystemUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(GameSystemBase))]
        public System.Type GameSystemType { get; private set; } = null;
         
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput SystemName { get; set; }
        
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueOutput GameSystem { get; set; }
        
        protected override void Definition()
        {
            base.Definition();
            SystemName = ValueInput<string>(nameof(SystemName), String.Empty);
            GameSystem = ValueOutput<GameSystemBase>(nameof(GameSystem));
            Requirement(SystemName, Input);
        }

        protected override ControlOutput In(Flow flow)
        {
            if(GameSystemType == null)
                throw new ArgumentNullException("GameSystemType");
            
            string systemName = flow.GetValue<string>(SystemName);
            
            if (string.IsNullOrEmpty(systemName))
                systemName = null;
            
            GameSystemBase system = Target?.RegisterSystem(GameSystemType, systemName);
            flow.SetValue(GameSystem, system);
            return base.In(flow);
        }
    }
}
